#include "client.h"

int threadInit(thread_t* thread){
    bzero(thread,sizeof(thread_t));
    return 0;
}

void* threadFunc(void* arg){
    thread_t* thread = (thread_t *)arg;
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = thread->port;
    addr.sin_addr.s_addr = thread->IP;
    int ret = connect(sockfd, (struct sockaddr *)&addr, sizeof(addr));
    ERROR_CHECK(ret, -1, "connect");
    //发送信息表示子线程
    train_t train;
    bzero(&train,sizeof(train));
    train.tag = TOKEN;
    send(sockfd,&train,sizeof(train),MSG_NOSIGNAL);
    //发送token和姓名
    train.length = strlen(thread->token) + 1;
    memcpy(train.data,thread->token,train.length);
    send(sockfd,&train,sizeof(train),MSG_NOSIGNAL);

    train.tag = USRNAME;
    train.length = strlen(thread->usrname) + 1;
    memcpy(train.data,thread->usrname,train.length);
    send(sockfd,&train,sizeof(train),MSG_NOSIGNAL);
    //检验
    recvn(sockfd,&train,sizeof(train));
    if(train.tag == 1){
        printf("验证不通过。\n");
        return NULL;
    }

    train.tag = thread->tag;
    train.length = strlen(thread->path) + 1;
    memcpy(train.data,thread->path,train.length);
    send(sockfd,&train,sizeof(train),MSG_NOSIGNAL);

    if(train.tag == PUTS){
        while(1){
            int ret = putfile_c_to_s(sockfd,train.data);
            if(ret == 0){
                break;
            }
        }
    }else if(train.tag == GETS){
        getfile_s_to_c(sockfd);
    }
    return NULL;
}

int makethread(thread_t* thread){
    pthread_t tid;
    pthread_create(&tid,NULL,threadFunc,thread);
    return 0;
}
